using System;

namespace IPD_GeneralLib
{
	/// <summary>
	/// 
	/// </summary>
	
public partial class IPDGeneral
 {
  const string IH_MAGIC = "Inter@ctive Pager Backup/Restore File\n";
   
  internal byte Ipd_Header_ver;
  internal byte Ipd_Header_namesep;

   
  internal static string[,] VirtualArray_SMS_Out;
  internal static string [] sCSV_colnames;
 
  internal static int iROW_TOWRITE;

  internal static string sIpd_filename = @".\Onedb_SMS.ipd";


static void Init_var_readCsv()
 {
   VirtualArray_SMS_Out = new string[IPD_GeneralLib.IPDGeneral.CMAXROW_VIRTUALARRAY, 6] ;
   for (int ii = 0 ; ii < CMAXROW_VIRTUALARRAY ; ii++)
      for (int ij = 0 ; ij < VirtualArray_SMS_Out.GetLength(1) ; ij++)
	       VirtualArray_SMS_Out[ii, ij] = "" ;

   iROW_TOWRITE = 0;
}

void Init_var_createIpd()
 {
   Ipd_Header_namesep = 0;
   Ipd_Header_ver = 2 ; // ????
}

void Clean_var_createIpd()
 {
   
  // Resize the virtual Array by real content (2 dim arrays). ONLY to reduce memory occupation
    int icol, irow, inbcols ; 
    inbcols =  VirtualArray_SMS_Out.GetLength(1) ;
    string[,] newArray = new string[iROW_TOWRITE, inbcols];
    //copy the contents of the old array to the new one
    for (irow = 0 ; irow < iROW_TOWRITE - 1 ; irow++)
        for (icol = 0 ; icol < inbcols ; icol++)
            newArray[irow,icol] = VirtualArray_SMS_Out[irow,icol] ;
    //set the original to the new array
    VirtualArray_SMS_Out = newArray;
  
  if (wb103 != null) // Other Dump binary buffer (debug purpose)
    {
     wb103.Close() ;
     wb103.Dispose();
     wb103 = null;
   }
   
   if (Output_IPD_File_binWriter != null) // Ipd creation
     {
      Output_IPD_File_binWriter.Close();
      Output_IPD_File_binWriter.Dispose();
    }
}

public static int Create_OneDB_Ipd()
 {
  int iret = CIPDERROR_NOERROR ;
  IPDGeneral pdbg = new IPDGeneral();  // pour appeler des fonctions non statiques à partir de celle-ci qui est statique

   pdbg.Init_var_createIpd();
   
   iret = pdbg.OutputIPD_prepare();
      
   if (iret == CIPDERROR_NOERROR)
       iret = pdbg.write_header_in_ipd();
      
   if (iret == CIPDERROR_NOERROR)
       iret = pdbg.write_dbnameblock_in_ipd("SMS Messages");
 
   int irow = 0;
   short hrecordhandle = 1;
   int irecorduniqid = 1000;
   int inbrows = iROW_TOWRITE - 1; // -1 because iROW_TOWRITE has 0 as columns names
   if (iret == CIPDERROR_NOERROR)
     for (irow = 0 ; irow < inbrows ; irow++) 
        {
         byte [] yDataRecordBlock = pdbg.prepare_datablock_for_ipd(irow, hrecordhandle, irecorduniqid);
         hrecordhandle++;
         irecorduniqid++;
         if (yDataRecordBlock == null)
            {
             iret = CIPDERROR_UnexpectedIpdEof;
             break;
          }
         iret = pdbg.write_datablock_in_ipd(irow, yDataRecordBlock) ;
         if (iret != CIPDERROR_NOERROR)
             break;
       }

   pdbg.Clean_var_createIpd();
   
   return(iret);
}

internal static int ReadCsvFile(string scsv_filename)
{
  int iret = CIPDERROR_NOERROR;
  int inbcolumns = 0;
  string smesstext = "";
  string stmp = "";
  bool brecordcomplete = true;
  int ifieldNOTcomplete = -1;
  int ilinesincsv = 0;
  bool bcolnamesconform = true;

 if (System.IO.File.Exists(scsv_filename) == false)
     return(CIPDERROR_FileNotFound) ;   // csv Not found

 Init_var_readCsv();

 try
   {
    using (System.IO.StreamReader sr = new System.IO.StreamReader(scsv_filename))
      {
        while (sr.Peek() >= 0) 
           {
            smesstext = sr.ReadLine() ;
            ilinesincsv++;
            if (brecordcomplete == true)
               iROW_TOWRITE++ ;
            if (ilinesincsv == (CMAXROW_VIRTUALARRAY - 1))
                return(CIPDERROR_TooManyLines_InFile);
            if (iROW_TOWRITE == 1) // columns names
              {
               sCSV_colnames = smesstext.Split(sdelimitercsv[0]);
               inbcolumns = sCSV_colnames.Length ;
               for (int ii = 0 ; ii < inbcolumns ; ii++)
                   {
                    stmp = sCSV_colnames[ii].Replace(" ", "");
                    if (stmp == "")
                       bcolnamesconform = false;
                  }
               if ((inbcolumns > 6) || (inbcolumns < 2) || (bcolnamesconform == false))
                   return (CIPDERROR_TooManyNotEnoughRows);
             }
              else {
                    // TODO traiter le cas ou un champ est sur plusieurs lignes
                    brecordcomplete = ifCsvrecordOnManylines(inbcolumns, smesstext,
                                                             brecordcomplete,
                                                             ref ifieldNOTcomplete);
                 }
        }
     }
  }
 
  catch { 
	     iret = CIPDERROR_FileError ;
    }

  
  return(iret) ;
}


internal static bool ifCsvrecordOnManylines(int inbcolumns, string smesstext,
                                            bool brecordcomplete,
                                            ref int ifieldNOTcomplete)
 {
  int ii = 0;
  int ilenline = smesstext.Length;
  int inbdelimiter = 0;
  int inbquote = 0;
  int icase = 0;
  string [] ssplittmp = new string[inbcolumns];
  char cquote = '"';
  bool bfirstpass = true;
  
  if (brecordcomplete == false)
      bfirstpass = false;
  // count the 'quotes' in this line
  for (ii = 0 ; ii < ilenline ; ii++)
      if (smesstext[ii] == cquote)
          inbquote++ ;
  // count the 'delimiter' in this line
  for (ii = 0 ; ii < ilenline ; ii++)
      if (smesstext[ii] == sdelimitercsv[0])
          inbdelimiter++ ;
  
  if ((inbquote == inbcolumns * 2) && (inbdelimiter == inbcolumns - 1))
     icase = 0; // all fields on this line
  if (inbquote > inbcolumns * 2)
     icase = 1; // some 'cquote' inside fields. Line complete or not
  if (inbquote < inbcolumns * 2)
     icase = 2; // multi lines: only 'message' field can be multilines
     
 switch (icase) {
     case 0:  // all fields are on this line
         ssplittmp = smesstext.Split(sdelimitercsv[0]) ;
         brecordcomplete = true;
         break;
     case 1:  // some 'cdelimiter' inside fields. 'message' field can be complete or not
         int inbquotetmp = 0;
         string stest = smesstext.Replace("\"\"", "") ;
         // after removing "", count the 'delimiter' in this line
         for (ii = 0 ; ii < stest.Length ; ii++)
             if (stest[ii] == cquote)
                 inbquotetmp++ ;
         if (inbquotetmp == inbcolumns * 2) // all fields are on this line
            {
              ssplittmp = smesstext.Split(sdelimitercsv[0]) ;
              brecordcomplete = true;
           }
             else {
                   ssplittmp = smesstext.Split(sdelimitercsv[0]) ;
                   ifieldNOTcomplete = inbdelimiter;
                   brecordcomplete = false;
               }
         break;
     case 2:
         ssplittmp = smesstext.Split(sdelimitercsv[0]) ;
         if (bfirstpass == true)
             ifieldNOTcomplete = inbdelimiter;
         brecordcomplete = false;
         break;
 }
 
//try {
   if (brecordcomplete == true)
       {
        for (ii = 0 ; ii < ssplittmp.Length ; ii++)
            VirtualArray_SMS_Out[iROW_TOWRITE-2, ii] = ssplittmp[ii];
     }
       else { // save or complete only the multilines 'message' field
             if (bfirstpass == true)
                {
                 for (ii = 0 ; ii < ssplittmp.Length ; ii++)
                     if (ssplittmp[ii] != null)
                         VirtualArray_SMS_Out[iROW_TOWRITE-2, ii] = ssplittmp[ii];
               }
                else 
                    {
                     VirtualArray_SMS_Out[iROW_TOWRITE-2, ifieldNOTcomplete] += ("\n" + smesstext);
                     string stmp = VirtualArray_SMS_Out[iROW_TOWRITE-2, ifieldNOTcomplete];
                     if (stmp[stmp.Length-1] == '"') // TODO test + intelligent a faire
                         brecordcomplete = true;
                           else brecordcomplete = false;
                  }
         }
// }
  
//  catch (Exception ex) 
//     {
//       }
  
  return(brecordcomplete) ;
}

byte [] prepare_datablock_for_ipd(int irow, short hrecordhandle, int irecorduniqid)
 {

  int ii = 0;
  byte [] yDataRecordBlock = null;
  
 try {
  string [] sfields = new string[sCSV_colnames.Length];
  string [] stmp = new string[sCSV_colnames.Length];
  for (ii = 0 ; ii < sCSV_colnames.Length ; ii++)
      sfields[ii] = VirtualArray_SMS_Out[irow, ii];
      //sfields[ii] = listCSV_realrows[irow][ii];
  for (ii = 0 ; ii < sfields.Length ; ii++)
     {
      sfields[ii] = @sfields[ii]; // clean
      sfields[ii] = sfields[ii].Substring(1, sfields[ii].Length - 2);// remove 1st and last "
   }
      
  string sDateSent     = "";
  string sDateReceived = "";
  string sStatus       = "";
  int iStatus = 0;
  string sFolder       = "";
  int iFolder = 0;
  string sPhone        = "";
  string sMessage      = "";
/////
  if (IPDGeneral.iSMS_fieldresolved[0] != -1)
      sDateSent = sfields[IPDGeneral.iSMS_fieldresolved[0]];
/////
  if (IPDGeneral.iSMS_fieldresolved[1] != -1)
      sDateReceived = sfields[IPDGeneral.iSMS_fieldresolved[1]];
  if (sDateReceived == "")
      sDateReceived = sDateSent;
  if (sDateSent == "")
      sDateSent = sDateReceived;
/////
  if (IPDGeneral.iSMS_fieldresolved[2] != -1)
      sStatus = sfields[IPDGeneral.iSMS_fieldresolved[2]];
  if ((sStatus != "1") && (sStatus != "0"))
      iStatus = 0; // if no status, sent by default
        else iStatus = int.Parse(sStatus);
/////
  if (IPDGeneral.iSMS_fieldresolved[3] != -1) // "0"=Sent box,  "1"=Inbox
      sFolder = sfields[IPDGeneral.iSMS_fieldresolved[3]];
  if (sFolder == "")
      if (iStatus  == 1)
          iFolder = 1;         // "Inbox";
            else iFolder = 0;  // Sent box;
  if ((iFolder != 1) && (iFolder != 0))
     iFolder = 0; // if no Folder, Sent box by default
/////
  if (IPDGeneral.iSMS_fieldresolved[4] != -1)
      sPhone = sfields[IPDGeneral.iSMS_fieldresolved[4]];
/////
  if (IPDGeneral.iSMS_fieldresolved[5] != -1)
      sMessage = sfields[IPDGeneral.iSMS_fieldresolved[5]];

  yDataRecordBlock = convertstrings2ipdbytes(sDateSent, sDateReceived,
                                                     iStatus, iFolder, sPhone, sMessage,
                                                     hrecordhandle, irecorduniqid);
  }
  
 catch {
        yDataRecordBlock = null;
    }
    
  return(yDataRecordBlock) ;
}

byte [] convertstrings2ipdbytes(string sDateSent, string sDateReceived,
                                int iStatus, int iFolder, string sPhone, string sMessage,
                                short hrecordhandle, int irecorduniqid)
 {
  byte [] yDataRecordBlock = null;
  int ii = 0;
  int ilenstringfield = 0;
  byte yfieldtype = 0;
  int ifolder1 = 0;
  int ifolder2 = 0;
 try {
// Fields seems to be always in this order: 1  9  11  2  4  7  12
// 4 fields below always exists but for what usage? Arrays below are complete (len + type + data)  
  byte [] yFIELDtype9  = new byte[] {8,0,9,  1,0,0,128,255,255,255,1};         // 8 bytes
  byte [] yFIELDtype11 = new byte[] {4,0,11, 0,0,0,0};                         // 4 bytes
  byte [] yFIELDtype7  = new byte[] {15,0,7, 0,1,32,25,0,0,0,0,0,0,1,1,0,0,0}; //15 bytes
  byte [] yFIELDtype12 = new byte[] {8,0,12, 0,0,0,0,0,163,2,0};               // 8 bytes
  
///// 1- DATES + STATUS + FOLDER ========================================================
// Date received, Date Sent, Status and Folder are in the same field
  byte [] yFIELDdatecomplete = new byte [64 + 3]; // This field always same length
  // Field len in IPD format
  yFIELDdatecomplete[0] = 64; // len in bytes
  yFIELDdatecomplete[1] = 0;
  // field type
  yfieldtype = 1; // field type = dates+folder+status
  yFIELDdatecomplete[2] = yfieldtype;
  // 'force' always Unicode. I hope with that there is no problems
  yFIELDdatecomplete[32] = 2;
  // other data in this field
  byte [] yDateSent = IPDGeneral.ConvertStringDate2IpdDateArray(sDateSent);
  // Pos 16 in field array
  Array.Copy(yDateSent, 0, yFIELDdatecomplete, 16, yDateSent.Length);
 
  byte [] yDateReceived = IPDGeneral.ConvertStringDate2IpdDateArray(sDateReceived);
  // Pos 24 in field array
  Array.Copy(yDateReceived, 0, yFIELDdatecomplete, 24, yDateReceived.Length);

  if ((iStatus != 0) && (iStatus != 1))
      iStatus = 0;
  
  if (iStatus == 0)
     {
      ifolder1 = 1;
      ifolder2 = 0;
    }
     else
           {
            ifolder1 = 1;
            ifolder2 = 0;
          }
          
  yFIELDdatecomplete[3]  = (byte) iStatus;
  yFIELDdatecomplete[4]  = (byte) ifolder1;
  yFIELDdatecomplete[11] = (byte) ifolder2;

///// 4- PHONE===========================================================================
  ilenstringfield = sPhone.Length;
  byte [] yPhone = new byte[ilenstringfield + 1 + 4];
  byte [] ybastard4 = new Byte [] {0, 0, 0, 0}; // Don't know why these 4 null bytes
  Array.Copy(ybastard4, 0, yPhone, 3, ybastard4.Length);
  for (ii = 0 ; ii < ilenstringfield ; ii++)
      yPhone[ii + 4] = (byte) sPhone[ii];
  yPhone[ii + 4] = 0;
  yfieldtype = 2; // field type = Phone number
  byte [] yFIELDPhone = composeCompletebytesfield(yPhone, yfieldtype);
  
///// 5- MESSAGE ========================================================================
  // First, convert UTF8 to UCS-2
  byte[] yMessageutf8 = System.Text.Encoding.UTF8.GetBytes (sMessage); // NO null at end of Message !!!
  byte[] yMessage = System.Text.Encoding.Convert(System.Text.Encoding.UTF8,
                                              System.Text.Encoding.GetEncoding(1201),yMessageutf8);

  ilenstringfield = yMessage.Length;
  yfieldtype = 4; // field type = Message
  byte [] yFIELDMessage = composeCompletebytesfield(yMessage, yfieldtype);

///// 9999- NOW Record Data block =======================================================
  int ilenhead = 13;
  int iposindatablock = 0;
  int ilendatarecordblock = ilenhead + 
                            yFIELDdatecomplete.Length +
                            yFIELDtype9.Length +
                            yFIELDtype11.Length +
                            yFIELDPhone.Length +
                            yFIELDMessage.Length +
                            yFIELDtype7.Length +
                            yFIELDtype12.Length;
  yDataRecordBlock        = new byte[ilendatarecordblock];

// DataBase ID 0
  yDataRecordBlock[0] = 0;
  yDataRecordBlock[1] = 0;
  iposindatablock = 2;
// total record len int32, 4 bytes
  byte [] yArraybytes = convertInt2bytesarray(ilendatarecordblock - 6); // minus extra length of field type 1
  Array.Copy(yArraybytes, 0, yDataRecordBlock, iposindatablock, yArraybytes.Length);
  iposindatablock += 4;
// Db version 0x05
  byte ydbver = 5;
  yDataRecordBlock[iposindatablock] = ydbver;
  iposindatablock += 1;
// record handle 2 bytes
  yArraybytes = short2bytearray_reversed(hrecordhandle);
  Array.Copy(yArraybytes, 0, yDataRecordBlock, iposindatablock, yArraybytes.Length);
  iposindatablock += 2;
// record uniq ID 4 bytes
  yArraybytes = convertInt2bytesarray(irecorduniqid);
  Array.Copy(yArraybytes, 0, yDataRecordBlock, iposindatablock, yArraybytes.Length);
  iposindatablock += 4;
  
// fields
  Array.Copy(yFIELDdatecomplete, 0, yDataRecordBlock, iposindatablock, yFIELDdatecomplete.Length);
  iposindatablock += yFIELDdatecomplete.Length;
  
  Array.Copy(yFIELDtype9, 0, yDataRecordBlock, iposindatablock, yFIELDtype9.Length);
  iposindatablock += yFIELDtype9.Length;
  
  Array.Copy(yFIELDtype11, 0, yDataRecordBlock, iposindatablock, yFIELDtype11.Length);
  iposindatablock += yFIELDtype11.Length;
  
  Array.Copy(yFIELDPhone, 0, yDataRecordBlock, iposindatablock, yFIELDPhone.Length);
  iposindatablock += yFIELDPhone.Length;
  
  Array.Copy(yFIELDMessage, 0, yDataRecordBlock, iposindatablock, yFIELDMessage.Length);
  iposindatablock += yFIELDMessage.Length;
  
  Array.Copy(yFIELDtype7, 0, yDataRecordBlock, iposindatablock, yFIELDtype7.Length);
  iposindatablock += yFIELDtype7.Length;
  
  Array.Copy(yFIELDtype12, 0, yDataRecordBlock, iposindatablock, yFIELDtype12.Length);
  iposindatablock += yFIELDtype12.Length;
 }
 
 catch {
        yDataRecordBlock = null;
     }
     
  return(yDataRecordBlock);
}


static byte [] composeCompletebytesfield(byte [] ydata, byte yfieldtype)
 {
  int ilenbytesfield  = 0;
  int iposindatablock = 0;
  byte [] y2bytes;
  byte [] yFIELDdata = null;
  short hlen;

  ilenbytesfield = ydata.Length;
  hlen = (short) ilenbytesfield;
  y2bytes = BitConverter.GetBytes(hlen);
  
  ilenbytesfield += 3; // len=2 bytes, type=1 byte

  yFIELDdata = new byte[ilenbytesfield];
  iposindatablock = 0;
  Array.Copy(y2bytes, 0, yFIELDdata, iposindatablock, y2bytes.Length);
  iposindatablock += y2bytes.Length;
  yFIELDdata[iposindatablock] = yfieldtype;
  iposindatablock += 1;
  Array.Copy(ydata, 0, yFIELDdata, iposindatablock, ydata.Length);
  
  return(yFIELDdata);
}

int write_datablock_in_ipd(int irow, byte [] yDataRecordBlock)
 {
  int iret = CIPDERROR_NOERROR;
 
  if (Output_IPD_File_binWriter == null)
      return(CIPDERROR_FileWriteError) ;
      
// No return for write, only an exception if error      
  try {
            Output_IPD_File_binWriter.Write(yDataRecordBlock);
     }
  
  catch {
         iret = IPDGeneral.CIPDERROR_FileWriteError;
      }

  return(iret) ;
}

int write_header_in_ipd()
 {
  int iret = CIPDERROR_NOERROR;
 
  if (Output_IPD_File_binWriter == null)
      return(CIPDERROR_FileWriteError) ;

   Int16 nb_db = 1;   // BigEndian. 1 database at the moment

   int ilenmagic = IH_MAGIC.Length;
   byte [] yhead = new byte[42];
   byte [] arraymagic = getmybytesfromstring(IH_MAGIC, ilenmagic);
   
   byte [] Array2bytes = short2bytearray_reversed(nb_db);
   
   Array.Copy(arraymagic, yhead, ilenmagic) ;
   yhead[ilenmagic] = Ipd_Header_ver;
   Array.Copy(Array2bytes, 0, yhead, ilenmagic + 1, 2) ;
   yhead[ilenmagic + 3] = Ipd_Header_namesep;
   
// No return for write, only an exception if error      
  try {
            Output_IPD_File_binWriter.Write(yhead);
     }
  
  catch {
         iret = CIPDERROR_FileWriteError;
      }
  
  return(iret) ;
}

int write_dbnameblock_in_ipd(string sdbname)
 {
  int iret = CIPDERROR_NOERROR;
 
  if (Output_IPD_File_binWriter == null)
      return(CIPDERROR_FileWriteError) ;

//================================
    sdbname = sdbname + "\0" ;
    
	int ilen = sdbname.Length;
	byte [] ynamedb;

	byte [] Array2bytes = BitConverter.GetBytes((Int16) ilen);
	ynamedb = IPDGeneral.getmybytesfromstring(sdbname, ilen);

//================================

// No return for write, only an exception if error      
  try {
            Output_IPD_File_binWriter.Write(Array2bytes);
            Output_IPD_File_binWriter.Write(ynamedb);
     }
  
  catch {
         iret = CIPDERROR_FileWriteError;
      }
  
  return(iret) ;

}

int OutputIPD_prepare()
 {
  int iret = CIPDERROR_NOERROR;
  
  try {
        if (Output_IPD_File_binWriter == null)
            Output_IPD_File_binWriter = new System.IO.BinaryWriter(System.IO.File.Open(sIpd_filename, System.IO.FileMode.Create));
   }
   
  catch {
          iret = CIPDERROR_FileCreateError;
       }
   
  return(iret) ;
}

static byte [] short2bytearray_NOTreversed(Int16 ileshort)
 {
   byte [] Array2bytes = new Byte[2] ;
   
   Array2bytes = BitConverter.GetBytes(ileshort);
   
   return(Array2bytes) ;
}

static byte [] short2bytearray_reversed(Int16 ileshort)
 {
   byte [] Array2bytes = new Byte[2] ;
   byte ytmpbyte ;
   
   Array2bytes = BitConverter.GetBytes(ileshort);
   ytmpbyte = Array2bytes[0] ;
   Array2bytes[0] = Array2bytes[1] ;
   Array2bytes[1] = ytmpbyte ;
   
   return(Array2bytes) ;
}

// Convert a string date to a 8 bytes array (internal date in Ipd file)
static byte [] ConvertStringDate2IpdDateArray(string sDate)
 {
   byte [] yArray8Bytes = new byte[8];
   double ddtmp = 0; // 64 bits
   try {
   DateTime dt = Convert.ToDateTime(sDate);
   dt = dt.ToUniversalTime();

   DateTime dtBASE1 = new DateTime(1970, 1 , 1) ;
   TimeSpan TS1 = dt.Subtract(dtBASE1);
   ddtmp = TS1.TotalMilliseconds;
   yArray8Bytes = IPDGeneral.convertDouble2bytesarray(ddtmp);
   }
   
   catch {
       }
   
   return(yArray8Bytes);
}

static byte [] convertInt2bytesarray(int itmp)
 {
// ddNb1 + (ddNb2 * 256) + (ddNb3 * 256 * 256) + (ddNb4 * 256 * 256 * 256)

  byte[] outBytes = new byte[4];
  int inb1, inb2, inb3, inb4, idivmult;
  
  idivmult = (int) Math.Pow(256, 3);
  inb1 = itmp / idivmult;
  itmp -= (inb1 * idivmult);
  
  idivmult = (int) Math.Pow(256, 2);
  inb2 = itmp / idivmult;
  itmp -= (inb2 * idivmult);
  
  idivmult = (int) Math.Pow(256, 1);
  inb3 = itmp / idivmult;
  itmp -= (inb3 * idivmult);
  
  idivmult = (int) Math.Pow(256, 0);
  inb4 = itmp / idivmult;
  itmp -= (inb4 * idivmult);

  outBytes[3] = (byte) inb1 ;
  outBytes[2] = (byte) inb2 ;
  outBytes[1] = (byte) inb3 ;
  outBytes[0] = (byte) inb4 ;

  return(outBytes);
}

static byte [] convertDouble2bytesarray(double ddtmp)
 {
  byte[] outBytes = new byte[8];
  double ddnb1, ddnb2, ddnb3, ddnb4, ddnb5, ddnb6, ddnb7, ddnb8;
  int inb1 = 0;
  int inb2 = 0;
  int inb3 = 0;
  int inb4 = 0; 
  int inb5 = 0;
  int inb6 = 0;
  int inb7 = 0;
  int inb8 = 0;

  try {
        ddnb1 = ddtmp / (double) Math.Pow(256, 7);
        ddnb1 = Math.Truncate(ddnb1) ;
        ddtmp -= (ddnb1 * Math.Pow(256, 7));
        inb1 = (int) ddnb1;
  
        ddnb2 = ddtmp / (double) Math.Pow(256, 6);
        ddnb2 = Math.Truncate(ddnb2) ;
        ddtmp -= (ddnb2 * Math.Pow(256, 6));
        inb2 = (int) ddnb2;
  
        ddnb3 = ddtmp / (double) Math.Pow(256, 5);
        ddnb3 = Math.Truncate(ddnb3) ;
        ddtmp -= (ddnb3 * Math.Pow(256, 5));
        inb3 = (int) ddnb3;
  
        ddnb4 = ddtmp / (double) Math.Pow(256, 4);
        ddnb4 = Math.Truncate(ddnb4) ;
        ddtmp -= (ddnb4 * Math.Pow(256, 4));
        inb4 = (int) ddnb4; // - 256;
  
        ddnb5 = ddtmp / (double) Math.Pow(256, 3);
        ddnb5 = Math.Truncate(ddnb5) ;
        ddtmp -= (ddnb5 * Math.Pow(256, 3));
        inb5 = (int) ddnb5; //- (256 * 256) - (inb4 * 256)); // OK
   
        ddnb6 = ddtmp / (double) Math.Pow(256, 2);
        ddnb6 = Math.Truncate(ddnb6) ;
        ddtmp -= (ddnb6 * Math.Pow(256, 2));
        inb6 = (int) ddnb6; // - (256 * 256) - (inb5 * 256 * 256));
  
        ddnb7 = ddtmp / (double) Math.Pow(256, 1);
        ddnb7 = Math.Truncate(ddnb7) ;
        ddtmp -= (ddnb7 * Math.Pow(256, 1));
        inb7 = (int) ddnb7; // - (256 * 256 * 256 * 256));
   
        ddnb8 = ddtmp / (double) Math.Pow(256, 0);
        ddnb8 = Math.Truncate(ddnb8) ;
        ddtmp -= (ddnb8 * Math.Pow(256, 0));
        inb8 = (int) ddnb8;
     }
  
  catch {
     }

  outBytes[7] = (byte) inb1 ;
  outBytes[6] = (byte) inb2 ;
  outBytes[5] = (byte) inb3 ;
  outBytes[4] = (byte) inb4 ;
  outBytes[3] = (byte) inb5 ;
  outBytes[2] = (byte) inb6 ;
  outBytes[1] = (byte) inb7 ;
  outBytes[0] = (byte) inb8 ;

  return(outBytes);
}

byte[] convertstring2bytearray(string str)
 {
   System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
   return(encoding.GetBytes(str));
}
    
 }
}
